package org.petstore.web.servlet;

import org.petstore.domain.*;
import org.petstore.service.CartService;
import org.petstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ViewCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String SINGIN_FORM = "/WEB-INF/jsp/account/SignonForm.jsp";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //Cart cart = (Cart)session.getAttribute("cart");
        Account account = (Account)session.getAttribute("account");
        CartService cartService = new CartService();
        /*String username = account.getUsername();
        List<CartItem> cart = cartService.selectItemByUsername(username);
        if(cart == null){
            cart = new ArrayList<CartItem>();
            session.setAttribute("cart", cart);
        }*/
        if(account != null) {
            String username = account.getUsername();
            //List<CartItem> cart = cartService.selectItemByUsername(username);

            List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");

            if (cart == null) {
                cart = new ArrayList<CartItem>();

            }
            cart = cartService.selectItemByUsername(username);


            session.setAttribute("cart", cart);
            request.getRequestDispatcher(VIEW_CART).forward(request, response);
            if(account != null){
                HttpServletRequest httpRequest= request;
                String strBackUrl = "http://" + request.getServerName() + ":" + request.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                String logInfo = logService.logInfo(" ") + strBackUrl + " 查看购物车 " + cart;
                logService.insertLogInfo(account.getUsername(), logInfo);
                //request.getRequestDispatcher(VIEW_CART).forward(request, response);
            }
        }
        else{
            request.getRequestDispatcher(SINGIN_FORM).forward(request, response);
        }
    }
}
